/*
 * Copyright (C) 2009 University of Washington
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package org.odk.collect.android.activities;

import org.odk.collect.android.R;
import org.odk.collect.android.database.FileDbAdapter;
import org.odk.collect.android.utilities.FileUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Responsible for displaying and deleting all the valid forms in the forms directory.
 * 
 *
 *       
 * changed for peqi web application - forms are integrated with the app in this version - 6/26/2011
 *
 */
public class FormManagerList extends ListActivity {

    private AlertDialog mAlertDialog;
    private Button mGetButton;

    private SimpleCursorAdapter mInstances;
    private ArrayList<Long> mSelected = new ArrayList<Long>();
        
    private ProgressDialog mProgressDialog;	// added for peqi web application - forms are integrated with the app in this version - 6/26/2011
    private static final int PROGRESS_DIALOG = 1; // added for peqi web application - forms are integrated with the app in this version - 6/26/2011


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.form_manage_list);                
        mGetButton = (Button) findViewById(R.id.get_button);
        ArrayList<String> forms = FileUtils.getFilesAsArrayList(FileUtils.FORMS_PATH);
        if (forms != null) {
        	mGetButton.setText(getString(R.string.refresh_forms));
        } else {
        	mGetButton.setText(getString(R.string.get_forms));
        }
        mGetButton.setOnClickListener(new OnClickListener() {            	
            public void onClick(View v) { 
            	showDialog(PROGRESS_DIALOG);
            	//ProgressDialog dialog = ProgressDialog.show(FormManagerList.this, getString(R.string.downloading_data), 
            	//		getString(R.string.please_wait), true);
                deleteSelectedFiles();               
            	downloadFormAndImages();  
            	//dialog.dismiss();
            	dismissDialog(PROGRESS_DIALOG);
                refreshData();                
                if (mInstances.isEmpty()) {
                    finish();
                }
            }        	
        });
        
        // buildView takes place in resume
    }


    private void refreshView() {
        // get all mInstances that match the status.
        FileDbAdapter fda = new FileDbAdapter();
        fda.open();
        fda.addOrphanForms();
        Cursor c = fda.fetchFilesByType(FileDbAdapter.TYPE_FORM, null);
        startManagingCursor(c);

        String[] data = new String[] {
                FileDbAdapter.KEY_DISPLAY, FileDbAdapter.KEY_META
        };
        int[] view = new int[] {
                R.id.text1, R.id.text2
        };

        // render total instance view
        mInstances =
            new SimpleCursorAdapter(this, R.layout.two_item_choice_none, c, data, view);
        setListAdapter(mInstances);        
        getListView().setChoiceMode(ListView.CHOICE_MODE_NONE); 
        getListView().setItemsCanFocus(false);
                
        for (int i = 0; i < mInstances.getCount(); i++) {
        	// get row id from db
        	Cursor cu = (Cursor) mInstances.getItem(i);
        	long k = cu.getLong(cu.getColumnIndex(FileDbAdapter.KEY_ID));
        	// add/remove from selected list
        	if (!mSelected.contains(k))
        		mSelected.add(k);        	        		
        }

        // cleanup
        fda.close();

    }

    private void refreshData() {
        if (mInstances != null) {
            mInstances.getCursor().requery();
        }
        mSelected.clear();

        refreshView();
    }


    /**
     * Deletes the selected files.First from the database then from the file system
     */
    private void deleteSelectedFiles() {
        FileDbAdapter fda = new FileDbAdapter();
        fda.open();

        // delete removes the file from the database first
        int deleted = 0;
        for (int i = 0; i < mSelected.size(); i++) {
            if (fda.deleteFile(mSelected.get(i))) {
                deleted++;
            }
        }

        // remove the actual files and close db
        fda.removeOrphanForms();
        fda.removeOrphanInstances(this);
        fda.removeOrphanMedia();
        fda.close();
    }


    @Override
    protected void onPause() {
        if (mAlertDialog != null && mAlertDialog.isShowing()) {
            mAlertDialog.dismiss();
        }
        super.onPause();
    }


    @Override
    protected void onResume() {
        // update the list (for returning from the remote manager)
        refreshData();
        super.onResume();
    }


    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        
    }
    
    /*
     * added for peqi web application - forms and media are integrated into application - 6/26/2011 - start
     */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case PROGRESS_DIALOG:
                mProgressDialog = new ProgressDialog(this);
                DialogInterface.OnClickListener loadingButtonListener =
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();                            
                        }
                    };
                mProgressDialog.setTitle(getString(R.string.downloading_data));
                mProgressDialog.setMessage(getString(R.string.please_wait));
                mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
                mProgressDialog.setIndeterminate(true);
                mProgressDialog.setCancelable(false);
                mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener);
                return mProgressDialog;
        }
        return null;
    }
    
    public void downloadFormAndImages() {     	
        	FileUtils.createFolder(FileUtils.FORMS_PATH);
        	createForms();
        	boolean mediaDir = FileUtils.createFolder(FileUtils.MEDIA_PATH);
        	if (mediaDir) {
        		createResourceFiles();
        	}       	
        	refreshData();
           
    }
    public void createForms() {
    	Context context = getApplicationContext();
    	FileUtils.initFormResources();
    	Set set = FileUtils.mFileResMap.entrySet();
    	Iterator i = set.iterator();
        try {
        	while(i.hasNext()) {
        		Map.Entry res = (Map.Entry)i.next();
        		File file = new File(FileUtils.FORMS_PATH, res.getValue().toString());
        		InputStream is = context.getResources().openRawResource(Integer.parseInt(res.getKey().toString()));
        		OutputStream os = new FileOutputStream(file);
        		byte[] data = new byte[is.available()];
        		is.read(data);
        		os.write(data);
        		is.close();
        		os.close();
        	}

        } catch (IOException e) {
            // Unable to create file, likely because external storage is
            // not currently mounted.
            Log.w("ExternalStorage", "Error writing file", e);
        }
   	
    }
    @SuppressWarnings("unchecked")
	public void createResourceFiles() {
    	Context context = getApplicationContext();
    	FileUtils.initImageResources();
    	Set set = FileUtils.mResourceMap.entrySet();
    	Iterator i = set.iterator();
        try {
        	while(i.hasNext()) {
        		Map.Entry res = (Map.Entry)i.next();
        		File file = new File(FileUtils.MEDIA_PATH, res.getValue().toString());
        		InputStream is = context.getResources().openRawResource(Integer.parseInt(res.getKey().toString()));
        		OutputStream os = new FileOutputStream(file);
        		byte[] data = new byte[is.available()];
        		is.read(data);
        		os.write(data);
        		is.close();
        		os.close();
        	}

        } catch (IOException e) {
            // Unable to create file, likely because external storage is
            // not currently mounted.
            Log.w("ExternalStorage", "Error writing file", e);
        }
   	
    }
    /*
     * added for peqi web application - forms and media are integrated into application - 6/26/2011 - end
     */
    
    
    public void progressUpdate(String currentFile, int progress, int total) {
        mProgressDialog.setMessage(getString(R.string.fetching_file, currentFile, progress, total));
    }

}
